package com.yuxin.tongyi.lsll.sub;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.yuxin.tongyi.lsll.R;
import com.yuxin.tongyi.lsll.common.Constants;
import com.yuxin.tongyi.lsll.common.TongyiTeaApplication;
import com.yuxin.tongyi.lsll.pojo.ClassObj;
import com.yuxin.tongyi.lsll.pojo.Event;
import com.yuxin.tongyi.lsll.pojo.EventInfo;
import com.yuxin.tongyi.lsll.pojo.LoginInfo;
import com.yuxin.tongyi.lsll.pojo.NodeEvent;
import com.yuxin.tongyi.lsll.pojo.Student;
import com.yuxin.tongyi.lsll.pojo.StudentInfo;
import com.yuxin.tongyi.lsll.select.SelectClassActivity;
import com.yuxin.tongyi.lsll.select.ShowDataActivity;
import com.yuxin.tongyi.lsll.select.ShowStudentActivity;
import com.yuxin.tongyi.lsll.sub.ShowPhotoDialog.ImageCallBack;
import com.yuxin.tongyi.lsll.thread.GetClassFirstThread;
import com.yuxin.tongyi.lsll.thread.GetFirstEventThread;
import com.yuxin.tongyi.lsll.util.HttpRequestUtil;
import com.yuxin.tongyi.lsll.util.PubUtil;

/**
 * 拍照上传界面
 * 
 */
public class CaremaPhotoUploadActivity extends BaseActivity {

	private static final int type = 0;

	private Button btnPhoto, btnPhotoLib, btnUpload, btnBack;
	private ImageView ivPhoto; // 照片预览
	private EditText titleText; // 标题
	private TextView edtBaby; // 幼儿

	private TextView tvClass;    //班级
	private String classId; // 班级id
	private String className; //班级名称
	private GetClassFirstThread mClassThread; //班级列表线程
	private boolean classFlag = false;

	private ProgressDialog dialog; // 加载进度
	private LoginInfo loginInfo;
	private MyHandler myHandler = null;
	private HttpRequestUtil request;

	private EventInfo eventInfo; // 事件信息
	private String nodeEventId; // 事件id
	private boolean eventFlag = false;
	private NodeEvent ne;
	private TextView eventText;
	private String thirdEventId;
	private String firstEventFiledName;
	private String secondEventFiledName;
	private String thirdEventFiledName;

	private StudentInfo studentInfo; // 学生信息
	private List<Student> students;
	public static String studentIds = ""; // 选择的学生 多个逗号分隔

	String CatchFilePath;
	private File TmpPicPath;
	public static String uploadUrl = "";
	public static String picId = "";// 选中图片
	
	

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sub_takephoto_modify);

		initView();
		initData();

		dialog = dialog.show(CaremaPhotoUploadActivity.this,
				Constants.MSG_LOADING, Constants.MSG_WAIT, true, true);

		request = new HttpRequestUtil();
		myHandler = new MyHandler();
		mClassThread = new GetClassFirstThread(this, myHandler);
		new Thread(mClassThread).start();
		//启动获取第一个领域的线程
		new Thread(new GetFirstEventThread(this, myHandler)).start();
	}

	public void initView() {
		titleText = (EditText) findViewById(R.id.sub_takephoto_edTitle);
		edtBaby = (TextView) findViewById(R.id.sub_takephoto_edBaby);
		edtBaby.setOnClickListener(stubtnClick);
		edtBaby.setFocusable(false);

		btnPhoto = (Button) findViewById(R.id.sub_takephoto_btnPhoto);
		btnPhotoLib = (Button) findViewById(R.id.sub_takephoto_btnPhotoStorage);
		btnUpload = (Button) findViewById(R.id.sub_takephoto_btnUpload);
		btnBack = (Button) findViewById(R.id.sub_takephoto_btnBack);
		btnPhoto.setOnClickListener(new onBtnClickListener());
		btnPhotoLib.setOnClickListener(new onBtnClickListener());
		btnUpload.setOnClickListener(new onBtnClickListener());
		btnBack.setOnClickListener(new onBtnClickListener());
		ivPhoto = (ImageView) findViewById(R.id.sub_takephoto_ivPhoto);
		
		tvClass = (TextView) findViewById(R.id.sub_takephoto_tvClass);
		tvClass.setOnClickListener(new onClassClick());

		eventText = (TextView) findViewById(R.id.mText_spField);
		//设置事件文本点击事件
		eventText.setOnClickListener(new MtextViewListener());
	}
	
	class onClassClick implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			Intent intent = new Intent();
			intent.setClass(CaremaPhotoUploadActivity.this, SelectClassActivity.class);
			startActivityForResult(intent, Constants.REQUEST_CODE_ClASS);
		}
	}

	private class MtextViewListener implements OnClickListener {
		@Override
		public void onClick(View arg0) {
			Intent mTextIntent = new Intent();
			//跳转到处理事件的Activity
			mTextIntent.setClass(CaremaPhotoUploadActivity.this,
					ShowDataActivity.class);
			startActivityForResult(mTextIntent, Constants.REQUEST_CODE_EVENT);
		}
	}

	public void initData() {
		try {
			loginInfo = (LoginInfo) TongyiTeaApplication.getMap().get(
					Constants.GLOBAL_LOGININFO);
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			CatchFilePath = getExternalCacheDir().toString() + File.separator
					+ "test.jpg";
		} catch (Exception e) {
			PubUtil.showToastLong(CaremaPhotoUploadActivity.this,
					"读取SD卡错误，请检查SD卡是否准备好");
			e.printStackTrace();
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case Constants.REQUEST_CODE_ClASS:
			if (resultCode == Activity.RESULT_OK) {
				Bundle b = data.getExtras();
				if(b != null){
					String SelectClassId = b.getString(Constants.SELECT_CLASS_ID);
					className = b.getString(Constants.SELECT_CLASS_NAME);
					if(!SelectClassId.equals(classId)){
						classId = SelectClassId;
						tvClass.setText(className);
						edtBaby.setText("");
						studentIds = "";
					}
				}
			}
			break;
		case Constants.REQUEST_CODE_STUDENTS:
			if (resultCode == Activity.RESULT_OK) {
				String studentNames = data.getStringExtra("studentNames");
				if(studentNames != null && !studentNames.equals("")){
					edtBaby.setText(studentNames);
				}
			}
			break;
		case Constants.REQUEST_CODE_EVENT:
			if (resultCode == RESULT_OK) {
				if (data != null) {
					EventInfo ei = (EventInfo) data
							.getSerializableExtra("eventInfo");
					Event e = (Event) data.getSerializableExtra("Event");
					ne = (NodeEvent) data
							.getSerializableExtra("nodeEvent");
					if (ei != null && e != null && ne != null
							&& eventText != null) {
						eventText.setText(ei.getFieldName() + "-"
								+ e.getEventName() + "-"
								+ ne.getNodeEventName());
					}
				}
			}
			break;
		case Constants.REQUEST_CODE_PHOTOLIB:
			if (resultCode == RESULT_OK) {
				ContentResolver resolver = getContentResolver();
				try {
					FileInputStream fis = new FileInputStream(CatchFilePath);
					Bitmap bm = BitmapFactory.decodeStream(fis);
					fis.close();
					bm = ResizeBitmap(bm, 800);
					saveImage(bm);
					if (bm != null) {
						ivPhoto.setImageBitmap(bm);
						ivPhoto.setAdjustViewBounds(true);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			break;
		}
	}

	/**
	 * 学生选择
	 */
	private OnClickListener stubtnClick = new OnClickListener() {
		public void onClick(View v) {
			try {
				Intent intent = new Intent();
				intent.setClass(CaremaPhotoUploadActivity.this,ShowStudentActivity.class);
				intent.putExtra("type",type);
				intent.putExtra("classId",classId);
				intent.putExtra("loginName",loginInfo.getLoginName());
				intent.putExtra("loginPassword",loginInfo.getPassword());
				
				startActivityForResult(intent, Constants.REQUEST_CODE_STUDENTS);
//				studialog.setStudents(new SelectStudent() {
//					@Override
//					public void setSelect(String StuStr) {
//						edtBaby.setText(StuStr);
//					}
//				});

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	/**
	 * 打开图库
	 */

	public void openPhotoLib() {
		try {
			ShowPhotoDialog photoList = new ShowPhotoDialog(
					CaremaPhotoUploadActivity.this);
			photoList.show();// 显示图片选择框
			photoList.setImageCallBack(new ImageCallBack() {
				@Override
				public void setImage(String uri) {
					Bitmap bitmap = BitmapFactory.decodeFile(uri);
					Bitmap bm = ResizeBitmap(bitmap, 800);
					saveImage(bm);
					if (bm != null) {
						ivPhoto.setImageBitmap(bm);
						ivPhoto.setAdjustViewBounds(true);
					}
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private class onBtnClickListener implements OnClickListener {
		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			// 拍照
			case R.id.sub_takephoto_btnPhoto:
				CaremaPhotoUploadActivity.this.openCamera();
				break;
			// 图库
			case R.id.sub_takephoto_btnPhotoStorage:
				CaremaPhotoUploadActivity.this.openPhotoLib();
				break;
			// 上传
			case R.id.sub_takephoto_btnUpload:
				CaremaPhotoUploadActivity.this.doUpLoad();
				break;
			// 返回
			case R.id.sub_takephoto_btnBack:
				CaremaPhotoUploadActivity.this.finish();
				break;
			}
		}
	}

	public void doUpLoad() {
		try {
			String title = titleText.getText().toString();
			if (ne == null) {
				nodeEventId = thirdEventId;
			}else{
				// 设置上传事件ID
				nodeEventId = ne.getNodeEventId();
			}
			if (studentIds == null || "".equals(studentIds)) {
				PubUtil.showToast(CaremaPhotoUploadActivity.this, "请选择宝宝");
				return;
			}
			if (classId == null || "".equals(classId)) {
				PubUtil.showToast(CaremaPhotoUploadActivity.this, "请选择班级");
				return;
			}
			if (title == null || "".equals(title)) {
				PubUtil.showToast(CaremaPhotoUploadActivity.this, "请选择标题");
				return;
			} else {
				if (title.length() > 15) {
					PubUtil.showToast(CaremaPhotoUploadActivity.this,
							"对不起,标题不能大于15个字");
					return;
				}
			}
			Drawable pic = ivPhoto.getDrawable();
			if (null == pic) {
				PubUtil.showToast(CaremaPhotoUploadActivity.this,
						"暂无照片可上传，请先拍照");
				return;
			}
			dialog = dialog.show(CaremaPhotoUploadActivity.this, "上传中", "请稍候");
			Message msg = myHandler.obtainMessage();
			msg.what = Constants.PHOTO_UPLOAD;
			myHandler.sendMessage(msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 拍照
	 */
	public void openCamera() {
		Intent getImageByCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(new File(CatchFilePath)));
		startActivityForResult(getImageByCamera, 1);
	}

	private void setClassData(ClassObj info) {
		classId = info.getClassId();
		className = info.getClassName();
		
		tvClass.setText(className);
	}
	
	/**
	 * 使用handler处理数据加载信息消息
	 * 
	 * 
	 */
	class MyHandler extends Handler {
		public MyHandler() {
		}

		public MyHandler(Looper L) {
			super(L);
		}

		public void handleMessage(Message msg) {
			try {
				super.handleMessage(msg);
				Bundle budle = msg.getData();
				switch (msg.what) {
				case Constants.TH_CLASS_ON:
					ClassObj classObj = (ClassObj) budle.getSerializable(Constants.STREAM_CLASS_FIRST);
					setClassData(classObj);
					classFlag = true;
					setDialogmiss();
					break;
				// 读取CLASS失败，加载缓存
				case Constants.TH_CLASS_OFF:
					PubUtil.showToastLong(CaremaPhotoUploadActivity.this, Constants.MSG_READCACHE);
					ClassObj classObj1 = (ClassObj) budle.getSerializable(Constants.STREAM_CLASS_FIRST);
					setClassData(classObj1);
					classFlag = true;
					setDialogmiss();
					break;
				case Constants.TH_EVENT_ON:
					eventInfo = (EventInfo) budle.getSerializable(Constants.STREAM_EVENT_FIRST);
					setFirstEvent(eventInfo);
					eventFlag = true;
					setDialogmiss();
					break;
				case Constants.TH_EVENT_OFF:
					PubUtil.showToastLong(CaremaPhotoUploadActivity.this, Constants.MSG_READCACHE);
					eventInfo = (EventInfo) budle.getSerializable(Constants.STREAM_EVENT_FIRST);
					setFirstEvent(eventInfo);
					eventFlag = true;
					setDialogmiss();
					break;
				case Constants.PHOTO_UPLOAD:
					UploadThread upload = new UploadThread();
					Thread thread = new Thread(upload);
					thread.start();
					break;
				case Constants.PHOTO_UPLOADMES:
					Bundle bundle = msg.getData();
					String message = bundle.getString("msg");
					dialog.dismiss();
					if (message != null && !"".equals(message)) {
						PubUtil.showDialog(CaremaPhotoUploadActivity.this,
								"提示", message, null, false);
					}
					break;
				case Constants.LOGIN_VALUE_RE: // 暂无数据
					new AlertDialog.Builder(CaremaPhotoUploadActivity.this)
							.setTitle("错误").setMessage("请重新登陆").show();
					dialog.dismiss();
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 获取首事件的数据,设置事件显示
	 */
	public void setFirstEvent(EventInfo eventInfo){
		firstEventFiledName = eventInfo.getFieldName();
		secondEventFiledName = eventInfo.getEvent().get(0).getEventName();
		thirdEventFiledName = eventInfo.getEvent().get(0).getNodeEvent().get(0).getNodeEventName();
		thirdEventId = eventInfo.getEvent().get(0).getNodeEvent().get(0).getNodeEventId();
		eventText.setText(firstEventFiledName + "-" + secondEventFiledName + "-" + thirdEventFiledName);
	}

	/**
	 * 关闭加载框
	 */
	public void setDialogmiss() {
		if (eventFlag == true && classFlag == true) {
			dialog.dismiss();
		}
	}


	/**
	 * 设置学生下拉列表
	 * 
	 * @param info
	 */
	public void setStudentList(StudentInfo info) {
		students = info.getStudent();
	}

	public static void setStudentIds(String studentIds) {
		CaremaPhotoUploadActivity.studentIds = studentIds;
	}

	/**
	 * 缩放
	 * 
	 * @param bitmap
	 * @param newWidth
	 * @return
	 */
	public Bitmap ResizeBitmap(Bitmap bitmap, int newWidth) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		float temp = ((float) height) / ((float) width);
		int newHeight = (int) ((newWidth) * temp);
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		bitmap.recycle();
		return resizedBitmap;
	}

	private void saveImage(Bitmap bm) {
		HashMap<Integer, Object> map = new HashMap<Integer, Object>();
		map.put(1, String.valueOf(System.currentTimeMillis()));
		map.put(2, new File(getExternalFilesDir("").getPath()));
		String strTempFile = (String) map.get(1);
		File myRecAudioDir = (File) map.get(2);
		try {
			TmpPicPath = File
					.createTempFile(strTempFile, ".jpg", myRecAudioDir);
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(TmpPicPath));
			bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			bos.flush();
			bos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 上传线程 模拟上传文件提交
	 * 
	 */
	class UploadThread implements Runnable {
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		String message = ""; // 上传文件信息

		public void run() {
			try {
				String title = URLEncoder.encode(
						titleText.getText().toString(), "UTF-8");
				URL url = new URL(HttpRequestUtil.ServerUrl
						+ HttpRequestUtil.uploadUrl + "?loginName="
						+ loginInfo.getLoginName() + "&pwd="
						+ loginInfo.getPassword() + "&studentId=" + studentIds
						+ "&nodeEventId=" + nodeEventId + "&classId=" + classId
						+ "&title=" + title + "&photoPath=test");
				HttpURLConnection con = (HttpURLConnection) url
						.openConnection();
				/* 允许Input、Output，不使用Cache */
				con.setDoInput(true);
				con.setDoOutput(true);
				con.setUseCaches(false);
				/* 设置传送的method=POST */
				con.setRequestMethod("POST");
				/* setRequestProperty */
				con.setRequestProperty("Connection", "Keep-Alive");
				con.setRequestProperty("Charset", "UTF-8");
				con.setRequestProperty("Content-Type",
						"multipart/form-data;boundary=" + boundary);
				/* 设置DataOutputStream */
				DataOutputStream ds = new DataOutputStream(
						con.getOutputStream());
				ds.writeBytes(twoHyphens + boundary + end);
				ds.writeBytes("Content-Disposition: form-data; "
						+ "name=\"file1\";filename=\"" + "test.jpg" + "\""
						+ end);
				ds.writeBytes(end);
				/* 取得文件的FileInputStream */
				FileInputStream fStream = new FileInputStream(TmpPicPath);
				/* 设置每次写入1024bytes */
				int bufferSize = 1024;
				byte[] buffer = new byte[bufferSize];
				int length = -1;
				/* 从文件读取数据至缓冲区 */
				while ((length = fStream.read(buffer)) != -1) {
					/* 将资料写入DataOutputStream中 */
					ds.write(buffer, 0, length);
				}
				ds.writeBytes(end);
				ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

				/* close streams */
				fStream.close();
				ds.flush();

				/* 取得Response内容 */
				InputStream is = con.getInputStream();
				int ch;
				StringBuffer b = new StringBuffer();
				while ((ch = is.read()) != -1) {
					b.append((char) ch);
				}
				/* 通知handler 将Response显示于Dialog */
				if (b != null) {
					String response = b.toString().trim();
					// 获取服务器返回状态
					String status = String.valueOf(response.charAt(response
							.lastIndexOf("</resultCode>") - 1));
					if ("0".equals(status)) {
						message = "上传成功";
					} else {
						message = "上传失败";
					}
				} else {
					message = "服务器异常,请稍后在试";
				}
				/* 关闭DataOutputStream */
				ds.close();
			} catch (Exception e) {
				message = "上传失败";
			}
			Message msg = myHandler.obtainMessage();
			msg.what = Constants.PHOTO_UPLOADMES;
			Bundle bundle = new Bundle();
			bundle.putString("msg", message);
			msg.setData(bundle);
			myHandler.sendMessage(msg);
		}
	}

}
